package com.eastelsoft.smartiot.bssserver.service.impl;

import com.eastelsoft.smartiot.bssserver.dao.TCmAppAuthorizeMapper;
import com.eastelsoft.smartiot.bssserver.domain.TCmAppAuthorize;
import com.eastelsoft.smartiot.bssserver.domain.TCmUserAccount;
import com.eastelsoft.smartiot.bssserver.service.RedisService;
import com.eastelsoft.smartiot.bssserver.service.TAppAuthorizeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.UUID;

@SuppressWarnings("ALL")
@Service
public class TAppAuthorizeServiceImpl implements TAppAuthorizeService {
    @Autowired
    private TCmAppAuthorizeMapper tCmAppAuthorizeMapper;
    @Autowired
    private RedisService redisService;
    protected Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 更新或者存储授权表的信息
     * @param tuser
     * @param appId
     * @param scope
     */
    @Override
    public void saveInfo(TCmUserAccount tuser, String appId, String scope) {

        // 用户登录逻辑
        log.info("用户用户名和密码正确。");
        TCmAppAuthorize tCmAppAuthorize = tCmAppAuthorizeMapper.selectByAppIDAndUserID(
                appId, tuser.getUserAccountId());
        if (tCmAppAuthorize!=null && !StringUtils.isEmpty(tCmAppAuthorize.getAuthorizeId())) {
            // 已经存在授权信息，更新授权信息
            log.info("已经存在授权信息，更新授权信息。");
            tCmAppAuthorize.setScope(StringUtils.isEmpty(scope)? "":scope);
            tCmAppAuthorizeMapper.updateByPrimaryKey(tCmAppAuthorize);
        } else {
            // 保存应用授权信息
            log.info("保存应用授权信息。");
            // 保存应用授权信息到数据库中
            tCmAppAuthorize=new TCmAppAuthorize();
            tCmAppAuthorize.setAuthorizeId(UUID.randomUUID().toString().replace("-", ""));
            tCmAppAuthorize.setAppId(appId);
            tCmAppAuthorize.setUserAccountId(tuser.getUserAccountId());
            tCmAppAuthorize.setScope(scope==null ? "":scope);
            tCmAppAuthorize.setOpenId(UUID.randomUUID().toString().replace("-", ""));
            tCmAppAuthorize.setAuthTime(new Date());
            tCmAppAuthorizeMapper.insert(tCmAppAuthorize);
        }

    }

    @Override
    public TCmAppAuthorize getByAppIDAnduserID(String appId, String userId) {
        return tCmAppAuthorizeMapper.selectByAppIDAndUserID(appId,userId);
    }

    @Override
    public TCmAppAuthorize findByOpenId(String openId) {
        return null;
    }
}
